﻿using MESTranslateToPLC.Schema.Response;

namespace MESTranslateToPLC.Service.BackgroudService;

public class ReadDataTimerService : BackgroundService
{
    private ModbusService _modbusService;
    private ILogger<ReadDataTimerService> _logger;
    private IHttpClientFactory _httpClientFactory;


    public ReadDataTimerService(ModbusService modbusService, ILogger<ReadDataTimerService> logger,
        IHttpClientFactory httpClientFactory)
    {
        _modbusService = modbusService;
        _logger = logger;
        _httpClientFactory = httpClientFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var client = _httpClientFactory.CreateClient("test");
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                if (_modbusService.IsConnected)
                {
                    var data = await _modbusService.ReadCoilsAsync(0, 1, 30);
                    var requestBody = new ModBusGetCoinsResponse
                    {
                        Address = 1,
                        Count = 30,
                        Values = data.ToList(),
                        SlaveAddress = 0
                    };
                    // _logger.LogInformation("Modbus连接正常,收到的数据为:{0}", data);
                    await client.PostAsJsonAsync("data", new
                    {
                        address = requestBody.Address,
                        count = requestBody.Count,
                        values = requestBody.Values,
                        slave_address = requestBody.SlaveAddress
                    }, stoppingToken);
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning("Modbus连接异常:{0}", e.Message);
            }
            finally
            {
                await Task.Delay(1000, stoppingToken);
            }
        }
    }
}